package com.heima.baidu.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.dfa.WordTree;
import com.alibaba.fastjson.JSON;
import com.heima.baidu.auth.AccessToken;
import com.heima.baidu.config.BaiDuConfig;
import com.heima.baidu.config.BaiDuConfigProperties;
import com.heima.baidu.response_entity.CheckResponse;
import com.heima.baidu.response_entity.DataDTO;
import com.heima.baidu.response_entity.HitsDTO;
import com.heima.baidu.service.BaiDuService;
import com.heima.baidu.utils.Base64Util;
import com.heima.baidu.utils.FileUtil;
import com.heima.baidu.utils.HttpUtil;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@EnableConfigurationProperties(BaiDuConfigProperties.class)
@Import(BaiDuConfig.class)
public class BaiDuServiceImpl implements BaiDuService {

    @Autowired
    private AccessToken accessToken;

    @Autowired
    private BaiDuConfigProperties baiDuConfigProperties;

    private static WordTree tree = new WordTree();

    private static List<String> list = new ArrayList<>();

    private static Snowflake snowflake = IdUtil.getSnowflake(1, 1);

    private static CheckResponse errorParmResponse = new CheckResponse();

    private static Integer checkNum = 0;

    /**
     * 初始化
     */
    @PostConstruct
    public void init() {
//        list = redisTemplate.opsForList().range("words_filter", 0, -1);
        if (CollectionUtils.isEmpty(list)) {
            try {
                Resource resource = new ClassPathResource("words.txt");
                InputStream is = resource.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String data = null;
                while ((data = br.readLine()) != null) {
                    if (StringUtils.isNotEmpty(data)) {
                        list.add(data);
                    }
                }
                br.close();
                isr.close();
                is.close();
//                redisTemplate.opsForList().rightPushAll("words_filter", list);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        tree.addWords(list);
//        tree.addWord("大土豆");
        errorParmResponse.setLogId(snowflake.nextId());
        errorParmResponse.setErrorCode(0);
        errorParmResponse.setErrorMessage("无效参数");
    }

//    /**
//     * 检查文本
//     *
//     * @param text
//     * @return
//     */
//    public CheckResponse checkText(String text) {
//        if (!checkParm(text)) return errorParmResponse;
//        long id = snowflake.nextId();
//        List<String> matchAll = tree.matchAll(text, -1, false, false);
//        matchAll = tree.matchAll(text, -1, false, true);
////        Assert.assertEquals(matchAll.toString(), "[大, 大土豆, 刚出锅]");
//        if (matchAll.size() > 0) {
//            CheckResponse checkResponse = new CheckResponse();
//            checkResponse.setLogId(id);
//            checkResponse.setConclusion("不合规");
//            checkResponse.setConclusionType(2);
//            checkResponse.setData(matchAll.stream().map(
//                    item -> {
//                        DataDTO dataDTO = new DataDTO();
//                        dataDTO.setConclusion("不合规");
//                        dataDTO.setConclusionType(2);
//                        dataDTO.setMsg("存在默认违禁词库不合规");
//                        dataDTO.setHits(Arrays.asList(
//                                new HitsDTO(
//                                        "自定义黑词库",
//                                        Collections.singletonList(item.toString()))));
//                        return dataDTO;
//                    }).collect(Collectors.toList())
//            );
//            return checkResponse;
//        }
//        log.info("调用百度接口：{}",text);
//        JSONObject response = aipContentCensor.textCensorUserDefined(text);
//        return JSON.parseObject(response.toString(), CheckResponse.class);
//    }
//
//    /**
//     * 根据本地路径检查图片
//     *
//     * @param filePath
//     * @return
//     */
//    public CheckResponse checkFileImage(String filePath) {
//        if (!checkParm(filePath)) return errorParmResponse;
//        //参数为本地图片路径
//        JSONObject response = aipContentCensor.imageCensorUserDefined(filePath, EImgType.FILE, null);
//        return JSON.parseObject(response.toString(), CheckResponse.class);
//    }
//
//    /**
//     * 根据本地文件检查图片
//     *
//     * @param file
//     */
//    public CheckResponse checkFileImage(File file) {
//        if (!checkParm(file)) return errorParmResponse;
//        // 参数为本地图片文件二进制数组
//        try {
//            InputStream fis = new FileInputStream(file);
//            byte[] bytes = FileCopyUtils.copyToByteArray(fis);
//            JSONObject response = aipContentCensor.imageCensorUserDefined(bytes, null);
//            return JSON.parseObject(response.toString(), CheckResponse.class);
//        } catch (Exception ex) {
//            log.info("transform file into bin Array 出错,{}", ex);
//            return errorParmResponse;
//        }
//    }
//
//    /**
//     * 检查网页图片
//     *
//     * @param url
//     * @return
//     */
//    public CheckResponse checkUrlImage(String url) {
//        if (!checkParm(url)) return errorParmResponse;
//        // 参数为url
//        JSONObject response = aipContentCensor.imageCensorUserDefined(url, EImgType.URL, null);
//        return JSON.parseObject(response.toString(), CheckResponse.class);
//    }
//
//    private boolean checkParm(Object parm) {
//        if (parm == null) {
//            return false;
//        }
//        return true;
//    }

    /**
     * 文本审核
     *
     * @param text 需要审核的文本
     * @return
     */
    @Override
    public CheckResponse checkText(String text) {
        List<String> matchAll = tree.matchAll(text, -1, false, false);
        matchAll = tree.matchAll(text, -1, false, true);
        if (matchAll.size() > 0) {
            long id = snowflake.nextId();
            CheckResponse checkResponse = new CheckResponse();
            checkResponse.setLogId(id);
            checkResponse.setConclusion("不合规");
            checkResponse.setConclusionType(2);
            checkResponse.setData(matchAll.stream().map(
                    item -> {
                        DataDTO dataDTO = new DataDTO();
                        dataDTO.setConclusion("不合规");
                        dataDTO.setConclusionType(2);
                        dataDTO.setMsg("存在默认违禁词库不合规");
                        dataDTO.setHits(Arrays.asList(
                                new HitsDTO(
                                        "自定义黑词库",
                                        Collections.singletonList(item.toString()))));
                        return dataDTO;
                    }).collect(Collectors.toList())
            );
            log.error("自定义词库审核未通过：{}", checkResponse);
            return checkResponse;
        }
        //获取access_token
//        String access_token = accessToken.getAuth();
        try {
            //设置请求的编码
            String param = "text=" + URLEncoder.encode(text, "UTF-8");
            //调用文本审核接口并取得结果
            String result = HttpUtil.post(baiDuConfigProperties.getCheckTextUrl(), baiDuConfigProperties.getAccessToken(), param);
            // JSON解析对象
            CheckResponse checkResponse = JSON.parseObject(result, CheckResponse.class);
            if (checkResponse.getErrorCode() != null || checkNum < 3) {
                checkNum++;
                String auth = accessToken.getAuth();
                checkResponse = JSON.parseObject(
                        HttpUtil.post(baiDuConfigProperties.getCheckTextUrl(), auth, param),
                        CheckResponse.class);
            }
            checkNum = 0;
            log.info("文本审核的响应：{}", checkResponse);
            return checkResponse;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 图像审核
     *
     * @param imagePath 需要审核的图片路径
     * @return
     */
    @Override
    public CheckResponse checkImage(String imagePath) {
        if (!new File(imagePath).exists()) {
            throw new NullPointerException("图片不存在");
        }
        //获取access_token
//        String access_token = accessToken.getAuth();
        try {
            //据文件路径读取byte[]数组
            byte[] imgData = FileUtil.readFileByBytes(imagePath);
            //Base64格式编码
            String imgStr = Base64Util.encode(imgData);
            //URLEncoder格式化编码
            String param = "image=" + URLEncoder.encode(imgStr, "UTF-8");
            //调用图像审核接口
            String result = HttpUtil.post(baiDuConfigProperties.getCheckImageUrl(), baiDuConfigProperties.getAccessToken(), param);

            //JSON解析对象
            CheckResponse checkResponse = JSON.parseObject(result, CheckResponse.class);
            return checkResponse;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
